﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DunLibrary.Dun;
using DunSilverlight.Comm;
using DunLibrary.CreditCard;

namespace DunSilverlight.Views
{
    public partial class CaseForm : UserControl
    {
        private IList<ArrearRecord> arrearRecords;//欠费记录
        private IList<CallRecord> callRecords;//催款记录
        private IList<CardholderContact> contacts;//联系信息
        private IList<InvestigateRequest> reqs;//调查记录
        private IList<VisitRecord> vrs; //外访记录

        private IList<DunLibrary.Base.ContactType> contactTypes;//联系方式类别
        

        public Case ArrearCase { get; set; }//案件

        public CaseForm(Case acase)
        {
            InitializeComponent();
            ArrearCase = acase;
            Loaded += new RoutedEventHandler(CaseForm_Loaded);
        }
        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void CaseForm_Loaded(object sender, RoutedEventArgs e)
        {
            DataContext = ArrearCase;

            //以后TabItem中的数据加载放到TabItem.Load事件中，避免不必要的服务器访问，现在就凑合了。
            LoadArrearRecords();//欠费记录(多个信用卡的列表)
            LoadContacts();
            LoadCallRecord();//催款记录
            LoadInvestigateRequests();
            LoadVisitRecords();
            LoadReturnRecord();
            LoadContactTypes();
            LoadComments();
            //TabItem数据加载结束。
        }

        /// <summary>
        /// 获取案件下面所有的欠费记录
        /// </summary>
        private void LoadArrearRecords()
        {
            ArrearRecordService.ArrearRecordServiceClient ser = new ArrearRecordService.ArrearRecordServiceClient();

            ser.GetListByHQLCompleted += (object sender, ArrearRecordService.GetListByHQLCompletedEventArgs e) =>
                {
                    try
                    {
                        int totalCount = 0;
                        arrearRecords = JsonSerializerHelper.JsonToEntities<ArrearRecord>(e.Result, out totalCount);

                        dgdArrearRecord.ItemsSource = arrearRecords;
                    }
                    catch (Exception ex)
                    {
                        Tools.ShowMessage(ex.Message, "", false);
                    }

                };
            ser.GetListByHQLAsync("from ArrearRecord  where CaseId=" + ArrearCase.Id);
        }

        private void LoadContactTypes()
        {
            Action<IList<DunLibrary.Base.ContactType>> callBack=(IList<DunLibrary.Base.ContactType> cts)=>
            {
                cmbContactType.ItemsSource = cts;
            };

            AppGlobal.GetContactTypes(callBack);
        }

        /// <summary>
        /// 读取电话联系方式 ContactTypeId=1
        /// </summary>
        private void LoadContacts()
        {
            CardholderContactService.CardholderContactServiceClient ser = new CardholderContactService.CardholderContactServiceClient();

            ser.GetListByHQLCompleted += (object sender, CardholderContactService.GetListByHQLCompletedEventArgs e) =>
            {
                try
                {
                    int totalCount = 0;

                    contacts = JsonSerializerHelper.JsonToEntities<CardholderContact>(e.Result, out totalCount);

                    dgdPhone.ItemsSource = contacts;
                }
                catch (Exception ex)
                {
                    Tools.ShowMessage(ex.Message, "", false);
                }
            };
            //NHibernate这里有个bug,不能直接使用Case属性名,必须给对象一个别名，然后再用.
            ser.GetListByHQLAsync("from CardholderContact as c where Owner.Id =" + ArrearCase.Holder.Id);
        }

        /// <summary>
        /// 读取电话催款记录
        /// </summary>
        private void LoadCallRecord()
        {
            CallRecordService.CallRecordServiceClient ser = new CallRecordService.CallRecordServiceClient();

            ser.GetListByHQLCompleted += (object sender, CallRecordService.GetListByHQLCompletedEventArgs e) =>
                {
                    try
                    {
                        int totalCount = 0;

                        callRecords = JsonSerializerHelper.JsonToEntities<CallRecord>(e.Result, out totalCount);

                        dgdCallRecord.ItemsSource = callRecords;

                        dgdAgree.ItemsSource = callRecords.Where(p => p.IsAgree);
                    }
                    catch (Exception ex)
                    {
                        Tools.ShowMessage(ex.Message, "", false);
                    }
                };
            //NHibernate这里有个bug,不能直接使用Case属性名,必须给对象一个别名，然后再用.
            ser.GetListByHQLAsync("from CallRecord as c where c.Case.Id=" + ArrearCase.Id);
        }
        /// <summary>
        /// 读取回款信息
        /// </summary>
        private void LoadReturnRecord()
        {
            ReturnRecordService.ReturnRecordServiceClient ser = new ReturnRecordService.ReturnRecordServiceClient();

            ser.GetListByHQLCompleted += (object sender, ReturnRecordService.GetListByHQLCompletedEventArgs e) =>
                {
                    int totalCount = 0;
                    IList<DunLibrary.Dun.ReturnRecord> rs = JsonSerializerHelper.JsonToEntities<ReturnRecord>(e.Result, out totalCount);

                    dgdReturnRecord.ItemsSource = rs;
                };
            //只查询当期的导入的回款金额
            string hql = string.Format("from ReturnRecord as r where r.Case.Id={0}", ArrearCase.Id);
            //string hql2 =string.Format("select r from Case as case left join case.ArrearRecords as a inner join a.Card as card,ReturnRecord as r where r.Card.Id=card.Id and case.Id={0}",ArrearCase.Id);
            ser.GetListByHQLAsync(hql);
        }

        /// <summary>
        /// 获取第三方调查申请
        /// </summary>
        private void LoadInvestigateRequests()
        {
            InvRequestService.InvestigateRequestServiceClient ser = new InvRequestService.InvestigateRequestServiceClient();

            ser.GetListByHQLCompleted += (object sender, InvRequestService.GetListByHQLCompletedEventArgs e) =>
                {
                    try
                    {
                        int totalCount = 0;

                        reqs = JsonSerializerHelper.JsonToEntities<InvestigateRequest>(e.Result, out totalCount);

                        dgdInvReq.ItemsSource = reqs;

                    }
                    catch (Exception ex)
                    {
                        Tools.ShowMessage(ex.Message, "", false);
                    }
                };
            ser.GetListByHQLAsync("from InvestigateRequest as inv where inv.Case.Id=" + ArrearCase.Id);
        }
        /// <summary>
        /// 获取外访记录
        /// </summary>
        private void LoadVisitRecords()
        {
            VisitRecordService.VisitRecordServiceClient ser = new VisitRecordService.VisitRecordServiceClient();

            

            ser.GetListByHQLCompleted += (object sender, VisitRecordService.GetListByHQLCompletedEventArgs e) =>
                {
                    int totalCount = 0;
                    vrs = JsonSerializerHelper.JsonToEntities<VisitRecord>(e.Result, out totalCount);
                    dgdVisitRecord.ItemsSource = vrs;
                };
            ser.GetListByHQLAsync("from VisitRecord as v where v.Case.Id="+ArrearCase.Id);
        }
        /// <summary>
        /// 读取批注信息
        /// </summary>
        private void LoadComments()
        {
            CaseCommentService.CaseCommentServiceClient ser = new CaseCommentService.CaseCommentServiceClient();

            ser.GetListByHQLCompleted += (object sender, CaseCommentService.GetListByHQLCompletedEventArgs e) =>
                {
                    int total = 0;
                    IList<CaseComment> comments = JsonSerializerHelper.JsonToEntities<CaseComment>(e.Result, out total);

                    dgdComment.ItemsSource = comments;
                };

            string hql=string.Format("from CaseComment as c where c.Case.Id={0}",ArrearCase.Id);
            ser.GetListByHQLAsync(hql);
        }

        /// <summary>
        /// 新增一个电话联系方式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddPhone_Click(object sender, RoutedEventArgs e)
        {
            CardholderContact contact = new CardholderContact();
            contact.Owner = ArrearCase.Holder;
            ContactForm frm = new ContactForm(contact);

            //新增成功后的回调
            frm.SaveCallBack = (CardholderContact chc) =>
                {
                    LoadContacts();
                };

            Tools.OpenWindow("新增电话", frm, null);
        }
        /// <summary>
        /// 设置电话有效
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSetValid_Click(object sender, RoutedEventArgs e)
        {
            CardholderContact chc=dgdPhone.SelectedItem as CardholderContact;

            if (chc != null)
            {
                chc.IsValid = true;
                //成功后的回调
                Action callback = () =>
                    {
                        dgdPhone.Items.Refresh();
                    };

                AppGlobal.SetContactValid(chc,callback);
            }
        }
        /// <summary>
        /// 在联系方式里面新增电话记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddCallRecord2_Click(object sender, RoutedEventArgs e)
        {
            CardholderContact chc = dgdPhone.SelectedItem as CardholderContact;

            if (chc != null)
            {
                AddCallRecord(chc.Content);
            }
        }
        /// <summary>
        /// 新增一个电话催款
        /// </summary>
        /// <param name="contact"></param>
        private void AddCallRecord(string contact)
        {
            if (!RightManagement.VerifyRight(RightManagement.Right_Process_Case))
            {
                Tools.ShowMessage("您没有委案处理的权限", "", false);
                return;
            }

            CallRecord callRecord = new CallRecord();

            callRecord.Case = this.ArrearCase;
            callRecord.CallTime = DateTime.Now;
            callRecord.Contact = contact;

            CallRecordForm frm = new CallRecordForm(callRecord,contacts);

            frm.SaveCallBack = (CallRecord cr) =>
                {
                    LoadCallRecord();//新增后重新加载电话催款记录
                };

            Tools.OpenWindow("新增电话催款", frm, null);
        }

        private void ViewCallRecord()
        {
            CallRecord cr = dgdCallRecord.SelectedItem as CallRecord;

            if (cr != null)
            {
                CallRecordForm frm = new CallRecordForm(cr,contacts);
                
                Tools.OpenWindow("查看电话催款",frm,null);
            }
        }

        private void btnSetUnValid_Click(object sender, RoutedEventArgs e)
        {
            CardholderContact chc = dgdPhone.SelectedItem as CardholderContact;

            if (chc != null)
            {
                chc.IsValid = false;
                //成功后的回调
                Action callback = () =>
                {
                    dgdPhone.Items.Refresh();
                };

                AppGlobal.SetContactValid(chc, callback);
            }
        }
        /// <summary>
        /// 从电话催款记录中增加催款记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddCallRecord1_Click(object sender, RoutedEventArgs e)
        {
            AddCallRecord(null);
        }
        /// <summary>
        /// 查看电话催款记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEditCallRecord1_Click(object sender, RoutedEventArgs e)
        {
            ViewCallRecord();
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnThridReq_Click(object sender, RoutedEventArgs e)
        {
            if (!RightManagement.VerifyRight(RightManagement.Right_Process_Case))
            {
                Tools.ShowMessage("您没有委案处理的权限", "", false);
                return;
            }

            InvestigateRequest reg = new InvestigateRequest();
            reg.Case = ArrearCase;
            //reg.Oper = AppGlobal.CurrentUser;
            reg.OperateTime = DateTime.Now;

            EditThridReq(reg);
        }
        /// <summary>
        /// 编辑调查申请
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEditThridReq_Click(object sender, RoutedEventArgs e)
        {
            InvestigateRequest invReq = dgdInvReq.SelectedItem as InvestigateRequest;

            if (invReq == null)
                return;

            EditThridReq(invReq);
        }
        /// <summary>
        /// 删除一个调查审核
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDeleteThridReq_Click(object sender, RoutedEventArgs e)
        {
            InvestigateRequest invReq = dgdInvReq.SelectedItem as InvestigateRequest;

            if (invReq == null)
                return;

            if (invReq.IsAllow)
            {
                Tools.ShowMessage("已经审核的调查申请不能被删除!", "", false);
                return;
            }

            InvRequestService.InvestigateRequestServiceClient ser = new InvRequestService.InvestigateRequestServiceClient();

            ser.DeleteByIdCompleted += (object sender1, InvRequestService.DeleteByIdCompletedEventArgs e1) =>
                {
                    LoadInvestigateRequests();
                    ser.CloseAsync();
                };
            ser.DeleteByIdAsync(invReq.Id);
        }

        /// <summary>
        /// 新增或编辑
        /// </summary>
        /// <param name="req"></param>
        private void EditThridReq(InvestigateRequest req)
        {
            ThridInvForm frm = new ThridInvForm(req);

            frm.SaveCallBack = (DunLibrary.Dun.InvestigateRequest r) =>
                {
                    LoadInvestigateRequests();
                };
           
            Tools.OpenWindow("新增第三方资料查询", frm, null);
        }
        /// <summary>
        /// 新增外访记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddVisit_Click(object sender, RoutedEventArgs e)
        {
            if (!RightManagement.VerifyRight(RightManagement.Right_Process_Case))
            {
                Tools.ShowMessage("您没有委案处理的权限", "", false);
                return;
            }

            VisitRecord vr = new VisitRecord();
            vr.Case = ArrearCase;
            vr.OperateTime = DateTime.Now;

            VisitForm frm = new VisitForm(vr);

            frm.SaveCallBack = (VisitRecord v) =>
                {
                    LoadVisitRecords();
                };

            Tools.OpenWindow("新增外访申请", frm);
        }

        /// <summary>
        /// 编辑外访记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEditVisit_Click(object sender, RoutedEventArgs e)
        {
            ViewVisitRecord();
        }

        private void ViewVisitRecord()
        {
            VisitRecord rec = dgdVisitRecord.SelectedItem as VisitRecord;

            if (rec != null)
            {
                VisitForm frm = new VisitForm(rec);

                Tools.OpenWindow("编辑外访记录", frm);
                
            }
        }
        /// <summary>
        /// 删除一个外放记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDeleteVisit_Click(object sender, RoutedEventArgs e)
        {
            VisitRecord rec = dgdVisitRecord.SelectedItem as VisitRecord;

            if (rec == null)
                return;

            if (rec.IsAllow)//假如已经审核
            {
                Tools.ShowMessage("已经审核的外访记录不能被删除!", "", false);
                return;
            }

            try
            {
                VisitRecordService.VisitRecordServiceClient ser = new VisitRecordService.VisitRecordServiceClient();

                ser.DeleteByIdCompleted += (object sender1, VisitRecordService.DeleteByIdCompletedEventArgs e1) =>
                    {
                        LoadVisitRecords();
                    };
                ser.DeleteByIdAsync(rec.Id);
                ser.CloseAsync();
            }
            catch (Exception ex)
            {
                Tools.ShowMessage(ex.Message, "", false);
            }
        }

        private void cmbContactType_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangedEventArgs e)
        {
            DunLibrary.Base.ContactType ct = cmbContactType.SelectedItem as DunLibrary.Base.ContactType;

            if (ct != null && contacts != null && contacts.Count > 0)
            {
                dgdPhone.ItemsSource = contacts.Where(p => (p as DunLibrary.Base.Contact).ContactType.Id == ct.Id);

                
            }

            btnAddCallRecord2.IsEnabled = ct.Id==1?true:false;

        }

        private void btnAddComment_Click(object sender, RoutedEventArgs e)
        {
            if (!RightManagement.VerifyRight(RightManagement.Right_Comment))
            {
                Tools.ShowMessage("您没有批注权限", "", false);
                return;
            }

            CaseComment cc = new CaseComment();
            cc.Case = ArrearCase;
            cc.Checker = AppGlobal.CurrentUser;
            cc.OpTime = DateTime.Now;

            CommentForm frm = new CommentForm(cc);

            frm.SaveCallBack = () =>
                {
                    LoadComments();
                };
            Tools.OpenWindow("新增一个批注", frm, null);
        }

        private void btnViewComment_Click(object sender, RoutedEventArgs e)
        {
            CaseComment cc = dgdComment.SelectedItem as CaseComment;

            if (cc != null)
            {
                CommentForm frm = new CommentForm(cc);
                frm.SaveCallBack = () =>
                    {
                        LoadComments();
                    };
                Tools.OpenWindow("查看一个批注", frm, null);
            }
        }
    }
}
